

var app=angular.module('myApp', []).
  config(['$routeProvider', function($routeProvider) {
  $routeProvider.
      when('/', {templateUrl: 'replace.html', controller: ListExpMstCtrl}).
      //when('/delete/', {templateUrl: 'replace.html', controller: ListExpMstCtrl}).      
      //when('/updte/', {templateUrl: 'replace.html', controller: ListExpMstCtrl}). 
      when('/cancel/', {templateUrl: 'replace.html', controller: ListExpMstCtrl}). 
      otherwise({redirectTo: '/'});
}]);


function ListExpMstCtrl($scope, $http,$window,$location,$filter)
 {	 
    $scope.currentPage = 0;
    $scope.pageSize = 25;
	$scope.Math = window.Math;
	$scope.c_ed = false;		$scope.s_ed = false;	
	$scope.p_ed = false;
	$scope.pfstbarr = [];		$scope.fstbarr = [];
	$scope.ostbarr = [];		$scope.postbarr = [];
	$scope.pfcardarr = [];		$scope.fcardarr = [];
	$scope.ocardarr = [];		$scope.pocardarr = [];
	$scope.assigned_stb = [];	$scope.assigned_card = [];
	$scope.newpairmast = {};	$scope.newrcardmast = {};	
	$scope.newrstbmast = {};
	
	$('.nav-tabs li:eq(1) a').tab('show');
    $http.get('replace_card_data.php?q=0').success(function(data) {
		$scope.rcardmast = data;		
    });
	
	$http.get('replace_card_data.php?q=3').success(function(data) {	
		for(var i=0;i<data.length;i++)
			$scope.fcardarr[i] = data[i];		
		});
	$http.get('replace_card_data.php?q=2').success(function(data) {	
		for(var i=0;i<data.length;i++)
			$scope.ocardarr[i] = data[i];		
		});
		
	$http.get('replace_stb_data.php?q=3').success(function(data) {	
		for(var i=0;i<data.length;i++)
			$scope.fstbarr[i] = data[i];		
		});
	$http.get('replace_pair_data.php?q=5').success(function(data) {	
		for(var i=0;i<data.length;i++){
			$scope.pfstbarr[i] = data[i].s;			
			$scope.pfcardarr[i] = data[i].c;
				}
	});
		
	$http.get('replace_pair_data.php?q=3').success(function(data) {	
		for(var i=0;i<data.length;i++){
			$scope.postbarr[i] = data[i].s;		
			$scope.assigned_stb[i] = data[i].s;		
			$scope.pocardarr[i] = data[i].c;		
			$scope.assigned_card[i] = data[i].c;		
		}
	});
	$http.get('replace_stb_data.php?q=2').success(function(data) {	
		for(var i=0;i<data.length;i++)
			$scope.ostbarr[i] = data[i];		
	});

	
	$scope.getParameterByName=function(name) {
		var results='';
		name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
		var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
			results = regex.exec(location.search);
		if(results && (name=='stb' || name=='card')){			
			$('.nav-tabs li:eq(0) a').tab('show');
			$http.get('replace_card_data.php?q=0').success(function(data) {
				$scope.pairmast = data;				
			});
		}		
		if(results && name=='ss'){			
			$('.nav-tabs li:eq(2) a').tab('show');
			$http.get('replace_stb_data.php?q=0').success(function(data) {
				$scope.rstbmast = data;					
			});
		}
		return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));								
	}
	$scope.newpairmast.oldstb = $scope.getParameterByName('stb');
	$scope.newpairmast.oldcard = $scope.getParameterByName('card');
	$scope.newrcardmast.oldcard = $scope.getParameterByName('cc');
	$scope.newrstbmast.oldstb = $scope.getParameterByName('ss');
		
	
    $scope.getRepPair=function()
	{
		$http.get('replace_pair_data.php?q=0').success(function(data) {
			$scope.pairmast = data;				
		});		
	}
	$scope.getRepCard=function()
	{
		$http.get('replace_card_data.php?q=0').success(function(data) {
			$scope.rcardmast = data;				
		});		
	}
	$scope.getRepStb=function()
	{
		$http.get('replace_stb_data.php?q=0').success(function(data) {
			$scope.rstbmast = data;
				
		});
	}
	$scope.cardgiven= function()
	{		
		if($scope.newrcardmast.oldcard.length>0){		
			var url='replace_card_data.php?q=1&oldcno='+$scope.newrcardmast.oldcard+'&newcno='+$scope.newrcardmast.newcard;	
			$http.get(url).success(function(data) {			
				//location.href=url;
				$scope.newrcardmast.stb = data;											
			});				
		}
	}
	$scope.stbgiven= function(i)
	{		
		if(i=='1'){		
			var url='replace_pair_data.php?q=1&stbno='+$scope.newpairmast.oldstb;
			$http.get(url).success(function(data) {		
				//location.href=url;				
				$scope.newpairmast.oldcard = data;											
			});				
		} 
		else{
			var url='replace_pair_data.php?q=1&stbno='+$scope.newpairmast.newstb;	
			$http.get(url).success(function(data) {		
				//location.href=url;				
				$scope.newpairmast.newcard = data;											
			});	
		}					
	}
	$scope.stbgiven2=function()
	{		
		if($scope.newrstbmast.oldstb){	
			var url = 'replace_stb_data.php?q=1&oldstbno='+$scope.newrstbmast.oldstb+'&newstbno='+$scope.newrstbmast.newstb;			
			$http.get(url).success(function(data) {
				//location.href=url;
				$scope.newrstbmast.card = data;											
			});		
		}
	}
	
	//Function to Edit Record
    $scope.edit = function(id, mast) {
		if(mast == 'rcardmast'){		
			for(i in $scope.rcardmast) {
				if($scope.rcardmast[i].id == id)
				{          
				   $scope.newrcardmast = angular.copy($scope.rcardmast[i]);				
				}
			}
			$scope.c_ed = true;
		}
		if(mast == 'rstbmast'){		
			for(i in $scope.rstbmast) {				
				if($scope.rstbmast[i].id == id)
				{          					
				   $scope.newrstbmast = angular.copy($scope.rstbmast[i]);				
				}
			}
			$scope.s_ed = true;
		}
		if(mast == 'pairmast'){			
			for(i in $scope.pairmast) {
				if($scope.pairmast[i].id == id)
				{          
				   $scope.newpairmast = angular.copy($scope.pairmast[i]);				
				}
			}
			$scope.p_ed = true;
		}
         
    };
    //Function to Delete Record
   $scope.dlt = function(id,table) {
      if (confirm('Do you really want to delete this record?')) 
        {
            var sql = "replace_cud.php?id="+id+"&table="+table+"&cud=d";							
            $http.post(sql).success(function(data)
            {          	
				//location.href=sql;			
				alert("Record "+id+" deleted successfully!");								
            });             
        }
      };
      
	
		//Function to Update Data 
		$scope.upd = function(mast,table) 
			{   	
				//var res1 = $scope.nullvalid(mast,table);			
				//var res2 = $scope.entryvalid(mast,table);		
				//var res3 = $scope.existvalid(mast,table);
				
				var sql = "replace_cud.php?"+"id="+mast.id+"&table="+table+"&dataset="+JSON.stringify(mast)+"&cud=u";	
				$http.post(sql).success(function(data)  
				{											
					//location.href=sql;
					alert("Record "+mast.id+" updated successfully!");							
					//$scope.cancel();						
				});														
						
			};
      
	 //Function to Insert Data 
	   $scope.sv = function(mast,table) 
	  	{			
			var res1 = $scope.nullvalid(mast,table);			
			var res2 = $scope.entryvalid(mast,table);			
			var res3 = $scope.existvalid(mast,table);				
			if(res1 == "y")
			{				
				if(res2 == "y")
				{					
					if(res3 == "y")
					{
						var sql="replace_cud.php?"+"id="+mast.id+"&table="+table+"&dataset="+JSON.stringify(mast)+"&cud=c";	
						$http.post(sql).success(function(data)  
						{													
							alert("Record added successfully!");
							//location.href=sql;							
						});	
					}
					else alert(res3);
				}
				else alert(res2);
			}
			else alert(res1);
			$scope.cancel();						
		};
		
		$scope.existvalid= function(mast,table)
		{
			var ret = '';				
			switch(table)
			{			
				case 'replacePair':					
					var ans = false;										
					//alert($scope.assigned_stb.length + ans);
					for(var i = 0; i < $scope.assigned_stb.length; i++)
					{										
						if(!ans && mast.newstb == $scope.assigned_stb[i])
						{								
							ans=true;														
						}
					}																				
					if(ans)
						ret += 'The new STB is already assigned \n';											
					if(ret.length==0)
						ret = "y";					
					break;
				
				case 'replaceCard':					
					var ans = false;										
					//alert($scope.assigned_card.length + ans);
					for(var i = 0; i < $scope.assigned_card.length; i++)
					{									
						if(!ans && mast.newcard == $scope.assigned_card[i])
						{								
							ans=true;														
						}
					}																				
					if(ans)
						ret += 'The new card is already assigned \n';											
					if(ret.length==0)
						ret = "y";
					break;
				
				case 'replaces':
					var ans = false;															
					for(var i = 0; i < $scope.assigned_stb.length; i++)
					{										
						if(!ans && mast.newstb == $scope.assigned_stb[i])
						{								
							ans=true;														
						}
					}																				
					if(ans)
						ret += 'The new STB is already assigned \n';											
					if(ret.length==0)
						ret = "y";
					break;								
			}			
			return ret;
		}
		
		$scope.entryvalid= function(mast,table)
		{			
			var ret = '';			
			switch(table)
			{
				case 'replacePair':
					var vos = false;
					var vns = false;
					var voc = false;
					var vnc = false;
					for(var i = 0; i < $scope.postbarr.length; i++)										
						if(!vos && mast.oldstb == $scope.postbarr[i])											
							vos = true;							
					for(var i = 0; i < $scope.pfstbarr.length; i++)
						if(!vns && mast.newstb == $scope.pfstbarr[i])
							vns = true;						
					for(var i = 0 ;i < $scope.pocardarr.length; i++)
						if(!voc && mast.oldcard == $scope.pocardarr[i])						
							voc = true;					
					for(var i = 0 ;i < $scope.pfcardarr.length; i++)							
						if(!vnc && mast.newcard == $scope.pfcardarr[i])											
							vnc = true;				
					if(!vos)
						ret += 'Please enter a valid old STB \n';
					if(!vns)
						ret += 'Please enter a valid new STB \n';
					if(!voc)
						ret += 'Please enter a valid old Card \n';
					if(!vnc)
						ret += 'Please enter a valid new Card \n';					
					if(ret.length==0)
						ret = "y";					
					break;
				
				case 'replaceCard':					
					var vns = false;
					var voc = false;
					var vnc = false;
							
					for(var i = 0 ;i < $scope.ocardarr.length; i++)
						if(!voc && mast.oldcard == $scope.ocardarr[i])						
							voc = true;
					
					for(var i = 0 ;i < $scope.fcardarr.length; i++)							
						if(!vnc && mast.newcard == $scope.fcardarr[i])											
							vnc = true;																						
					if(!voc)
						ret += 'Please enter a valid old Card \n';
					if(!vnc)
						ret += 'Please enter a valid new Card \n';					
					if(ret.length==0)
						ret = "y";
					break;
				
				case 'replaces':
					var vos = false;
					var vns = false;							
					for(var i = 0; i < $scope.ostbarr.length; i++)										
						if(!vos && mast.oldstb == $scope.ostbarr[i])											
							vos = true;							
					for(var i = 0; i < $scope.fstbarr.length; i++)
						if(!vns && mast.newstb == $scope.fstbarr[i])
							vns = true;													
																			
					if(!vos)
						ret += 'Please enter a valid old STB \n';
					if(!vns)
						ret += 'Please enter a valid new STB \n';												
					if(ret.length==0)
						ret = "y";
					break;								
			}			
			return ret;
		}
		
		$scope.nullvalid= function(mast,table)
		{			
			var ret = '';
			switch(table)
			{
				case 'replacePair':
					if(!mast.oldstb || !mast.newstb || !mast.oldcard || !mast.newcard || !mast.rdate )			
						ret = 'Please fill all the fields marked with *';
					else ret = 'y';
					break;
				
				case 'replaceCard':					
					if(!mast.oldcard || !mast.newcard || !mast.rdate )			
						ret = 'Please fill all the fields marked with *';
					else ret = 'y';
					break;
				
				case 'replaces':
					if(!mast.oldstb || !mast.newstb || !mast.rdate )			
						ret = 'Please fill all the fields marked with *';
					else ret = 'y';
					break;								
			}
			return ret;
		}
	  //Function to Clear 
        $scope.cancel= function()
		{
			$scope.activePath = null;
			$scope.activePath = $location.path('replace.php');
		};
      
 }
    
        //Custom Filter Function to sort the record.
    app.filter('startingFrom', function() 
    {
            return function(input, start) 
            {
                start = +start; //parse to int
                return input.slice(start);
            };
    });
	
	app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
		};
	});
	app.directive('capitalize', function () {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, modelCtrl) {
                var capitalize = function (inputValue) {
                    if (angular.isUndefined(inputValue))
                        return;
 
                    var capitalized = inputValue.toUpperCase();
                    if (capitalized !== inputValue) {
                        modelCtrl.$setViewValue(capitalized);
                        modelCtrl.$render();
                    }
                    return capitalized;
                };
                modelCtrl.$parsers.push(capitalize);
                capitalize(scope[attrs.ngModel]);  // capitalize initial value
            }
        };
    });
	
	
 app.directive('myMaxlength', function() {
  return {
    require: 'ngModel',
    link: function (scope, element, attrs, ngModelCtrl) {
      var maxlength = Number(attrs.myMaxlength);
      function fromUser(text) {
          if (text.length > maxlength) {
            var transformedInput = text.substring(0, maxlength);
            ngModelCtrl.$setViewValue(transformedInput);
            ngModelCtrl.$render();
			alert(maxlength+" character limit reached...");
            return transformedInput;			
          } 
          return text;
      }
      ngModelCtrl.$parsers.push(fromUser);
    }
  }; 
});

app.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'yy-mm-dd',
                onSelect: function (date) {
                    scope.$apply(function () {
                        ngModelCtrl.$setViewValue(date);
                    });											
                }				
            });			
        }
    };
});      

/*app.directive('myBlur', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind('blur', function () {
                //apply scope (attributes)
                scope.$apply(attr.myBlur);
                //return scope value for focusing to false
                scope.$eval(attr.myFocus + '=false');
            });
        }
    };
});*/